<!-- 出入院信息 入院信息 AdmissionInformation -->
<template>
  <div class="page-center">
    <div class="medical-form">
      <el-form :model="formData" label-width="140px" class="info-form" label-position="left">
        <el-divider content-position="left">
          <h3>入院信息</h3>
        </el-divider>

        <el-row :gutter="12">
          <!-- 入院信息 -->
          <el-col :span="24">
            <el-card class="box-card" shadow="never">
              <div slot="header" class="clearfix">
                <span>入院基本信息</span>
              </div>
              <el-form-item label="入院时间">
                <div class="display-value info-value">{{ display(formatDate(formData.admissionTime)) }}</div>
              </el-form-item>
              <el-form-item label="入院科室">
                <div class="display-value info-value">{{ display(formData.admissionDepartment) }}</div>
              </el-form-item>
              <el-form-item label="入院病区">
                <div class="display-value info-value">{{ display(formData.admissionWard) }}</div>
              </el-form-item>
              <el-form-item label="入院床位号">
                <div class="display-value info-value">{{ display(formData.admissionBedNumber) }}</div>
              </el-form-item>
              <el-form-item label="转科科室">
                <div class="display-value info-value">{{ display(formData.transferDepartment) }}</div>
              </el-form-item>
            </el-card>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import { hos } from '@/api/dataEntry/AdmissionDischargeInformation'

export default {
  name: 'AdmissionInformation',
  data() {
    return {
      formData: {
        id: 0,
        admissionTime: '',
        admissionDepartment: '',
        admissionWard: '',
        admissionBedNumber: '',
        transferDepartment: ''
      },
      loading: false
    }
  },
  computed: {
    ...mapGetters('patient', ['robustPatientId', 'patientFallbackData'])
  },
  watch: {
    robustPatientId: {
      handler(newId) {
        if (newId) {
          this.loadData(newId)
        } else {
          this.resetForm()
        }
      },
      immediate: true
    }
  },
  async mounted() {
    // 如果当前没有患者信息，尝试从存储恢复
    if (!this.robustPatientId) {
      const restored = await this.restorePatientFromStorage()
      if (restored) {
        this.loadData(restored.id || restored.patientId)
      }
    }
  },
  methods: {
    ...mapActions('patient', ['restorePatientFromStorage']),

    async loadData(patientId) {
      if (this.loading) return

      this.loading = true
      try {
        const res = await hos({ recordId: patientId })
        this.handleResponseData(res)
      } catch (error) {
        console.error('加载入院信息失败:', error)
        this.applyFallbackData()
      } finally {
        this.loading = false
      }
    },

    handleResponseData(res) {
      const payload = res?.data?.data ?? res?.data ?? res ?? {}

      if (payload && Object.keys(payload).length > 0) {
        this.formData = {
          ...this.formData,
          ...payload
        }
      }
    },

    applyFallbackData() {
      const patient = this.patientFallbackData
      if (patient) {
        // 从患者数据中提取可能的入院信息
        const admissionData = {
          admissionTime: patient.admissionTime,
          admissionDepartment: patient.admissionDepartment || patient.admissionDept,
          admissionWard: patient.admissionWard,
          admissionBedNumber: patient.admissionBedNumber,
          transferDepartment: patient.transferDepartment || patient.transferDept
        }

        // 过滤掉空值，避免覆盖现有数据
        Object.keys(admissionData).forEach(key => {
          if (admissionData[key] !== undefined && admissionData[key] !== null && admissionData[key] !== '') {
            this.formData[key] = admissionData[key]
          }
        })
      }
    },

    resetForm() {
      this.formData = {
        id: 0,
        admissionTime: '',
        admissionDepartment: '',
        admissionWard: '',
        admissionBedNumber: '',
        transferDepartment: ''
      }
    },

    display(val) {
      if (val === null || val === undefined || String(val).trim() === '') return '-'
      return val
    },

    formatDate(date) {
      if (!date) return ''
      // 简单的日期格式化
      if (typeof date === 'string') {
        return date.replace('T', ' ').replace(/\.\d+Z?$/, '')
      }
      if (date instanceof Date) {
        return date.toLocaleString()
      }
      return String(date)
    }
  }
}
</script>

<!-- 引入共享样式 -->
<style src="@/styles/shared.css"></style>

<style scoped>
</style>
